define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init();

            var table1 = $("#table1");

            // 初始化表格
            table1.bootstrapTable({
                extend: {
                    index_url: 'approach/index' + location.search,
                    add_url: 'approach/add',
                    edit_url: 'approach/edit',
                    // del_url: 'approach/del',
                    // multi_url: 'approach/multi',
                    table: 'approach',
                },
                url: 'approach/index' + location.search,
                pk: 'id',
                sortName: 'id',
                undefinedText:'',
                // search:false,
                showToggle:false,
                singleSelect:true,
                showExport:false,
                toolbar: "#toolbar1",
                columns: [
                    [
                        {checkbox: true},
                        {field: '', title: __('序号'),operate:false,table: table1,width:'50px',formatter:Table.api.formatter.natureorder},
                        // {field: 'name', title: __('Name')},
                        {
                          field: 'name',
                          title: __('Name'),
                          width:'100px',
                          halign:'left',
                          align:'left',
                          // style:"",
                          formatter:function(value,row,index){
                              //此处对value值做判断，不然value为空就会报错
                              if(row.name&&row.name.length<=10){
                                return"<span title ='"+row.name+"'>"+row.name+"</span>";
                              }
                              if(row.name&&row.name.length>10){
                                return"<span title ='"+row.name+"'>"+row.name.substring(0,9)+"...</span>";
                              }
                            }
                        },

                        {field: 'inspect_time', halign:'left', align:'left', width:'80px',title: __('Inspect_time'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime,datetimeFormat:'YYYY-MM-DD'},
                        // {field: 'inspect_time_desc', title: __('Inspect_time'),operate:false},
                        {field: 'inspect_address',  halign:'left',align:'left',width:'120px',title: __('Inspect_address')},
                        {field: 'leader_ids', title: __('Leader_ids'),visible:false},
                        // {field: 'leader_names', title: __('Leader_ids'),operate:false},
                        {
                            field: 'leader_names',
                            halign:'left',
                            align:'left',
                            title: __('Leader_ids'),
                            width:'70px',
                            formatter:function(value,row,index){
                              //此处对value值做判断，不然value为空就会报错
                              if(row.leader_names&&row.leader_names.length<=8){
                                return"<span title ='"+row.leader_names+"'>"+row.leader_names+"</span>";
                              }
                              if(row.leader_names&&row.leader_names.length>8){
                                return"<span title ='"+row.leader_names+"'>"+row.leader_names.substring(0,6)+"...</span>";
                              }
                            }
                        },
                        // {field: 'accompany_name', title: __('Accompany_name')},
                        {
                          field: 'accompany_name',
                           halign:'left',
                          align:'left',
                          title: __('Accompany_name'),
                          width:'120px',
                          formatter:function(value,row,index){
                              //此处对value值做判断，不然value为空就会报错
                              if(row.accompany_name&&row.accompany_name.length<=8){
                                return"<span title ='"+row.accompany_name+"'>"+row.accompany_name+"</span>";
                              }
                              if(row.accompany_name&&row.accompany_name.length>8){
                                return"<span title ='"+row.accompany_name+"'>"+row.accompany_name.substring(0,6)+"...</span>";
                              }
                            }
                        },

                        // {field: 'inspect_memo', title: __('Inspect_memo')},
                        {
                          field: 'inspect_memo',
                          title: __('Inspect_memo'),
                           halign:'left',
                          align:'left',
                          width:'150px',
                          formatter:function(value,row,index){
                              //此处对value值做判断，不然value为空就会报错
                              if(row.inspect_memo&&row.inspect_memo.length<=12){
                                return"<span title ='"+row.inspect_memo+"'>"+row.inspect_memo+"</span>";
                              }
                              if(row.inspect_memo&&row.inspect_memo.length>12){
                                return"<span title ='"+row.chargedep_names+"'>"+row.inspect_memo.substring(0,11)+"...</span>";
                              }
                            }
                        },
                        {field: 'chargedep_ids',  halign:'left',align:'left', title: __('Chargedep_ids'),visible:false},
                        // {field: 'chargedep_names', title: __('Chargedep_ids'),operate:false},
                        {
                          field: 'chargedep_names',
                          title: __('Chargedep_ids'),  halign:'left',align:'left',width:'150px',
                          formatter:function(value,row,index){
                              //此处对value值做判断，不然value为空就会报错
                              if(row.chargedep_names&&row.chargedep_names.length<=15){
                                return"<span title ='"+row.chargedep_names+"'>"+row.chargedep_names+"</span>";
                              }
                              if(row.chargedep_names&&row.chargedep_names.length>15){
                                return"<span title ='"+row.chargedep_names+"'>"+row.chargedep_names.substring(0,14)+"...</span>";
                              }
                            }
                        },
                        // {field: 'project_status_text', title: __('项目状态'),operate:false},
                        {field: 'project_status_name', title: __('项目状态'),
                        formatter:function(value,row,index){
                              //此处对value值做判断，不然value为空就会报错
                              if(row.project_time&&row.project_status_name)
                                return"<span>"+row.project_status_name+"<br/>"+row.project_time_text+"</span>";
                              else if(row.project_status_name)
                                return"<span>"+row.project_status_name+"</span>";
                              else
                                return"<span></span>";
                            }
                        },
                        {field: 'add_memo', title: __('备注'), halign:'left',align:'left',width:'130px',operate:false},

                        {field: 'status',title:'状态',operate:false, halign:'left',align:'left',
                            width:'80px',
                            formatter: function (value,row,index) {
                                if(value == 1)
                                {
                                    if(Config.isSuperAdmin)
                                        return '<a href="approach/checkedit/ids/'+row.id+'" class="btn btn-primary   btn-addtabs btn-xs" title="审核">待审核</a>';
                                    else
                                        return '<a href="javascript:;" class="btn btn-primary   btn-xs" title="审核">待审核</a>';
                                }
                                if(value == 0)
                                    if(Config.isSuperAdmin)
                                        return '<a href="approach/checkedit/ids/'+row.id+'" class="btn btn-success  btn-addtabs btn-xs " title="已审核">已审核</a>';
                                    else
                                        return '<a href="javascript:;" class="btn btn-success btn-xs ">已审核</a>';
                                if(value == -1)
                                    return '<a href="approach/initedit/ids/'+row.id+'" class="btn btn-danger btn-xs btn-dialog" data-icon="fa fa-pencil" data-title="编辑">待提交</a>';
                            }
                        }
                        // {field: 'operate', title: __('Operate'), table: table1, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ],
                // rowStyle:function(row,index){
                //     var style = {};
                //     // var classes =  ["gray", "red", "yellow", "aqua", "blue", "navy", "teal", "olive", "lime", "fuchsia", "purple", "maroon"];

                //     if(row.is_add == 1 )
                //         style={css:{'color':'#ff0000'}};
                //     if(row.reject_memo_status == 1)
                //         style={css:{'color':'blue'}};
                //     // console.log(style);
                //     return style;
                // }
            });

            // 为表格绑定事件
            Table.api.bindevent(table1);
            Controller.api.bindeventTable(table1);

            // table.on('load-success.bs.table', function (e, data) {
            //     //这里可以获取从服务端获取的JSON数据
            //     console.log(data);
            //     //这里我们手动设置底部的值
            //     $(".th").text(data.extend.money);
            //     $("#price").text(data.extend.price);
            // });
            var table2 = $("#table2");

            // 初始化表格
            table2.bootstrapTable({
                url: 'approach/index' + location.search,
                pk: 'id',
                sortName: 'id',
                toolbar: "#toolbar2",
                queryParams:function(params){
                    // console.log(params);
                    params.filter = JSON.parse(params.filter);
                    params.op = JSON.parse(params.op);
                    params.filter.status = 1;
                    params.op.status = '=';
                    // params.filter.is_important = 0;
                    // params.op.is_important = '=';
                    params.filter = JSON.stringify(params.filter);
                    params.op = JSON.stringify(params.op);
                    return params;
                },
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name')},
                        {field: 'chargedep_ids', title: __('Chargedep_ids'),visible:false},
                        {field: 'chargedep_names', title: __('Chargedep_ids'),operate:false},
                        {
                            field: 'check',
                            width: "120px",
                            title: __('审核'),
                            table: table2,
                            events: Table.api.events.operate,
                            // visible: Config.isSuperAdmin ? true:false,
                            buttons: [
                                {
                                    name: 'check',
                                    text: '审核',
                                    title: __('审核'),
                                    classname: 'btn btn-xs btn-warning  btn-magic btn-addtabs',
                                    icon: 'fa fa-folder-o',
                                    url: 'approach/checkedit',
                                }
                            ],
                            formatter: Table.api.formatter.buttons
                            // formatter: function (value, row, index) {
                            //     // console.log(Config.isSuperAdmin)
                            //     // if(Config.isSuperAdmin){
                            //         return Table.api.formatter.buttons.call(this, value, row, index);
                            //     }
                            //     return '';
                            // }
                        }
                        // {field: 'operate', title: __('Operate'), table: table1, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ],
                rowStyle:function(row,index){
                    var style = {};
                    if(row.is_add == 1 )
                        style={css:{'color':'#ff0000'}};
                    return style;
                }
            });



            // 为表格绑定事件
            Table.api.bindevent(table2);

            var parenttable = table1.closest('.bootstrap-table');
            var options = table1.bootstrapTable('getOptions');
            var toolbar = $(options.toolbar, parenttable);
            $(toolbar).on('click', ".btn-detail", function () {
                var that = this;
                //循环弹出多个编辑框
                $.each(table1.bootstrapTable('getSelections'), function (index, row) {
                    var url = 'approach/detail';
                    row = $.extend({}, row ? row : {}, {ids: row[options.pk]});
                    var url = Table.api.replaceurl(url, row, table1);
                    var icon = 'fa fa-info';
                    Backend.api.addtabs(url, row.name, icon);
                    // Fast.api.open(url, __('详情'), $(that).data() || {});
                });
            });

        },
        add: function () {
            $(".project_status").change(function(){
                if($(this).val() > 1)
                    $(".project_time").css("display","block");
                else
                    $(".project_time").css("display","none");
            })

            Controller.api.bindevent();
        },
        detail: function (){
            $(".btn-print").click(function (){
                var html = $(".print").html();
                var bodyHtml = document.body.innerHTML;
                document.body.innerHTML = html;
                window.print();
                document.body.innerHTML = bodyHtml;
            });

            $(".info").click(function(event) {
                var that = this;
                var ids = $(that).data("ids");
                var url ='approach/detail/ids/' + ids ;
                var icon = 'fa fa-info';
                Backend.api.addtabs(url, $(that).data('name'), icon);
            })

        },
        edit: function () {
            Controller.api.bindevent();
            $(".single_submit").click(function(event) {
                var item_id = $(this).data("item_id");

                // var value_name = $("#"+item_id).attr("name");
                var value = $("#"+item_id).val();

                var desc_value = $("#"+item_id+'_submit_desc').val();
                var required = 1;

                if(Config.isSuperAdmin ==1)
                    required = 0;

                var data = {};

                if(!value )
                {
                    Layer.alert(__('请填写修改内容'));
                    return false;
                }
                console.log(required);
                if(required && !desc_value)
                {
                    Layer.alert(__('请填写修改原因'));
                    return false;
                }

                if (item_id=='project_status'&&value>1)
                {
                    var project_time = $("#project_time").val();
                    if(!project_time){
                        Layer.alert(__('请填写时间'));return false;
                    }
                    data['project_time'] = project_time;
                }

                data['row[value]'] = value;
                data['row[desc_value]'] = desc_value;

                data.item_id = item_id;

                $.ajax({
                //几个参数需要注意一下
                    type: "POST",//方法类型
                    dataType: "json",//预期服务器返回的数据类型
                    url: location.href ,//url
                    data: data,
                    success: function (ret) {
                        if(ret.code == 1)
                        {
                            Layer.alert(__('提交成功'), function(index){
                                location.reload();
                            });
                        }

                        // location.reload();
                    },
                    error : function(error) {
                        console.log(error);
                    }
                });
            });

            $(".all_submit").click(function(event) {
                var errors = [];
                var data = {};
                $(".form_value").each(function(){
                    // console.log($(this))

                    var item_id = $(this).attr('id');
                    var item_value = $(this).val();
                    console.log(item_id);
                    if(item_id )
                    {
                        // console.log(item_id+','+item_value);
                        var item_label =  $("#"+item_id+"_label").html();
                        var item_value_desc = $("#"+item_id+"_submit_desc").val();
                        var required = 1;
                        if(Config.isSuperAdmin)
                            required = 0;
                        // var item_required = $("#"+item_id+'_submit_desc').data('required');
                        if(item_value  && required && !item_value_desc)
                        {
                            errors.push('请填写'+item_label+'修改原因');
                        }

                        if(item_value)
                            data['row['+item_id+']'] = item_value;
                        if(item_value_desc)
                            data['row['+item_id+'_submit_desc]'] = item_value_desc;


                        if (item_id=='project_status'&&item_value>1)
                        {
                            var project_time = $("#project_time").val();
                            if(!project_time){
                                Layer.alert(__('请填写时间'));return false;
                            }
                            data['project_time'] = project_time;
                        }
                    }
                });
                console.log(data);
                console.log(errors)
                if( errors.length > 0){
                    Layer.alert(errors.join("<br>"));
                    return false;
                }

                if($.isEmptyObject(data))
                {
                    Layer.alert('您没有要提交的数据，请填写后再提交');
                    return false;
                }

                $.ajax({
                //几个参数需要注意一下
                    type: "POST",//方法类型
                    dataType: "json",//预期服务器返回的数据类型
                    url: 'approach/initedit/ids/' + Config.ids,//url
                    data: data,
                    success: function (ret) {
                        if(ret.code == 1)
                            Layer.alert(__('提交成功'), function(index){
                                location.reload();
                            });
                        else{
                             Layer.alert(ret.msg);
                        }
                        // location.reload();
                    },
                    error : function(error) {
                        console.log(error);
                    }
                })
            })
            $(".project_status").change(function(){
                if($(this).val() > 1)
                    $(".project_time").css("display","block");
                else
                    $(".project_time").css("display","none");
            })
            
        },
        initedit: function () {
            Controller.api.bindevent();
        },
        checkedit:function() {
            $(".all_submit").click(function(event) {
                // console.log($(this).data("item_id"));
                var that = this;
                Layer.confirm(__('确定所有要通过审核吗?'), {
                    icon: 3,
                    title: '提示'
                }, function (index) {
                    $.ajax({
                        //几个参数需要注意一下
                        type: "POST",//方法类型
                        dataType: "json",//预期服务器返回的数据类型
                        url: "approach/checkedit/ids/"+ Config.ids,
                        success: function (ret) {
                            Layer.alert(__('提交成功'), function(index){
                                parent.location.reload();
                            });
                        },
                        error : function(error) {
                            console.log(error);
                        }
                    });
                    Layer.close(index);
                });

            });

            $(".btn-rejectmemo").click(function(event) {
                // alert("aaa");
                var that = this;

                var url = 'approach/rejectmemo/ids/' + Config.ids;

                Fast.api.open(url, __('驳回备注'),  {});
            });

        },
        rejectmemo:function() {
            Form.api.bindevent($("form[role=form]"));
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            bindeventTable: function (table) {
                var parenttable = table.closest('.bootstrap-table');
                //Bootstrap-table配置
                var options = table.bootstrapTable('getOptions');
                // console.log(options);
                //Bootstrap操作区
                var toolbar = $(options.toolbar, parenttable);

                table.on('dbl-click-row.bs.table', function (e, row, element, field) {
                    var url = options.extend.edit_url;
                     row = $.extend({}, row ? row : {}, {ids: row[options.pk]});
                    var url = Table.api.replaceurl(url, row, table);
                    var icon = 'fa fa-pencil';
                    Backend.api.addtabs(url, '编辑', icon);
                    // $('.btn-modi', element).trigger("click");
                });
                // console.log(toolbar);
                // $(".btn-customedit").click(function(event) {
                //     /* Act on the event */alert("aaaa");
                // });
                // alert("aaaa");
                // console.log(toolbar)
                $(toolbar).on('click', ".btn-customedit", function () {
                    var that = this;
                    //循环弹出多个编辑框
                    console.log(Config.chargedep_id);
                    $.each(table.bootstrapTable('getSelections'), function (index, row) {
                        var url = options.extend.edit_url;
                        row = $.extend({}, row ? row : {}, {ids: row[options.pk]});
                        var url = Table.api.replaceurl(url, row, table);
                        var icon = 'fa fa-pencil';
                        if(row.chargedep_ids)
                        {
                            var chargedep_ids_arr = row.chargedep_ids.split(',');

                            idx= chargedep_ids_arr.findIndex(function(item){
                                return parseInt(item) == parseInt(Config.chargedep_id);
                            })
                        }


                        if(Config.isSuperAdmin || idx!=-1 )
                            Backend.api.addtabs(url, '编辑', icon);

                        else
                            Layer.alert(__('此项目仅供查看'));


                        // Fast.api.open(url, __('Edit'), $(that).data() || {});
                    });
                });
            }
        }
    };
    return Controller;
});